﻿using Abp.Domain.Repositories;
using Abp.UI;
using shenghua.Common.WordNodes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Basics.MemberLevels
{
    public class MemberLevelManager : WordNodeManager<MemberLevel>
    {
        public MemberLevelManager(IRepository<MemberLevel> memberLevelRepository)
            : base(memberLevelRepository)
        {
        }

        public override async Task<MemberLevel> Add(MemberLevel memberLevel)
        {
            memberLevel.Level = _repository.GetAll().Max(r => r.Level) + 1;
            return await base.Add(memberLevel);
        }

        public async Task<MemberLevel> GetByLevel(int level)
        {
            MemberLevel memberLevel = _repository.GetAll().Where(r => r.Level == level).FirstOrDefault();
            if(memberLevel == null)
            {
                throw new UserFriendlyException($"不存在等级{level}");
            }
            return memberLevel;
        }

        public async Task DeleteLast()
        {
            int count = await base.Count();
            if(count > 0)
            {
                var query = _repository.GetAll();
                int maxId = query.Max(r => r.Id);
                await base.Delete(maxId);
            }
        }

        public override async Task<List<MemberLevel>> GetAll(int? parentId = null)
        {
            return _repository.GetAll().OrderBy(r => r.Level).ToList();
        }
    }
}
